package juc_09_ReadWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo01 {

    public static void main(String[] args) {
        MyCache02 cache = new MyCache02();

        for (int i = 0; i < 9; i++) {
            final String temp = String.valueOf(i);
            new Thread(()->{
                cache.put(temp, temp);
            }, String.valueOf(i)).start();
        }

        for (int i = 0; i < 9; i++) {
            final String temp = String.valueOf(i);
            new Thread(()->{
                cache.get(temp);
            }, String.valueOf(i)).start();
        }
    }
}

class MyCache01 {
    private volatile Map<String, Object> data = new HashMap();

    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + " 写入 " + key);
        data.put(key, value);
        System.out.println(Thread.currentThread().getName() + " 写入 " + key + " 完成");
    }

    public Object get(String key) {

        System.out.println(Thread.currentThread().getName() + " 读取 " + key);
        Object value = data.get(key);
        System.out.println(Thread.currentThread().getName() + " 读取 " + key + " 完成");
        return value;
    }
}

class MyCache02 {
    private volatile Map<String, Object> data = new HashMap();
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 写入 " + key);
            data.put(key, value);
            System.out.println(Thread.currentThread().getName() + " 写入 " + key + " 完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public Object get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 读取 " + key);
            Object value = data.get(key);
            System.out.println(Thread.currentThread().getName() + " 读取 " + key + " 完成");
            return value;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        return null;
    }
}
